package com.haiyou.dc.kafka.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haiyou.common.util.R;
import com.haiyou.dc.kafka.config.Constant;
import com.haiyou.dc.kafka.entity.Movie;
import com.haiyou.dc.kafka.service.MovieService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

/**
 * @author root
 * @date 2020-02-23 15:41:09
 */
@RestController
@RequestMapping("/movie")
@Slf4j
@Api(tags = "电影")
public class MovieController {

    @Autowired
    private KafkaTemplate kafkaTemplate;
    @Autowired
    private MovieService movieService;

    @ApiOperation(value = "保存数据")
    @PutMapping("/save")
    public R save(@RequestBody Movie movie) {
        movieService.insertSelective(movie);
        return R.ok();
    }

    @ApiOperation(value = "查看数据")
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id) {
        Movie movie = movieService.selectByPrimaryKey(id);
        ListenableFuture listenableFuture = kafkaTemplate.send(Constant.topic, JSON.toJSONString(movie));
        listenableFuture.addCallback(
                o -> log.info("消息发送成功,{}", o.toString()),
                throwable -> log.info("消息发送失败,{}" + throwable.getMessage())
        );
        return R.ok(movie);
    }

    @ApiOperation(value = "修改数据")
    @PostMapping("/update")
    public R update(@RequestBody Movie movie) {
        movieService.updateByPrimaryKeySelective(movie);
        return R.ok();
    }

    @ApiOperation(value = "删除数据")
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable("id") Integer id) {
        movieService.deleteByPrimaryKey(id);
        return R.ok();
    }

    @ApiOperation(value = "查看列表数据")
    @GetMapping("/list/{pageNum}/{pageSize}")
    public R list(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {
        Example example = new Example(Movie.class);
        example.orderBy("id").desc();
        Page<Movie> page = PageHelper.startPage(pageNum, pageSize, true, false, false);
        movieService.selectByExample(example);
        PageInfo<Movie> info = new PageInfo<>(page.getResult());
        return R.ok(info);
    }

}